package com.bilibili.juc.cf;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureanyOfDemo {

    public static void main(String[] args) {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(new Random().nextInt(5000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("#future1 finish ......");
            return "Result from CompletableFuture 1";
        });

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(new Random().nextInt(5000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("**future2 finish ......");
            return "Result from CompletableFuture 2";
        });

        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(new Random().nextInt(5000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("@@@future3 finish ......");
            return "Result from CompletableFuture 3";
        });

        List<CompletableFuture<String>> futures = Arrays.asList(future1, future2, future3);
        CompletableFuture<String>[] cfArr = new CompletableFuture[]{future1, future2, future3};

        //CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(cfArr);
        CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(futures.toArray(new CompletableFuture[0]));
        try {
            Object result = anyFuture.get();
            System.out.println("Result: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}